<?php

namespace Xrfg\Wallet\ETH\Traits;

use phpseclib\Math\BigInteger;

trait ETHHelper
{
    public function num2hex($num)
    {
        $bigInteger = new BigInteger($num, 10);
        $hex = ltrim($bigInteger->toHex(), '0');
        if (!$hex) {
            return '0x0';
        }

        return '0x'.$hex;
    }

    public function wei2ether($wei, $decimals = 18)
    {
        /** @var \phpseclib\Math\BigInteger $quotient */
        /** @var \phpseclib\Math\BigInteger $residue */
        list($quotient, $residue) = (new BigInteger($wei, 16))
            ->divide(new BigInteger(pow(10, $decimals)));

        $number = $quotient->toString();
        $residue = $residue->toString();

        // 余数部分有小数点，去掉小数点
        if (strpos($residue, '.') !== false) {
            $residue = substr($residue, 0, strpos($residue, '.'));
        }

        if ($residue) {
            $number .= '.'.rtrim(str_pad($residue, $decimals, '0', STR_PAD_LEFT), '0');
        }

        return $number;
    }

    public function ether2wei($num, $decimals = 18)
    {
        if (str_contains($num, '.')) {
            list($integer, $decimal) = explode('.', $num);
            $decimal = mb_substr($decimal, 0, $decimals);
        } else {
            $integer = $num;
        }

        $integer = (new BigInteger($integer, 10))
            ->multiply(new BigInteger(pow(10, $decimals), 10));
        if (isset($decimal)) {
            $decimal = (new BigInteger($decimal, 10))
                ->multiply(new BigInteger(pow(10, $decimals - mb_strlen($decimal)), 10));
            $integer = $integer->add($decimal);
        }

        return '0x'.ltrim($integer->toHex(), '0');
    }
}
